package com.mrti.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mrti.shop.pojo.User;
import com.mrti.shop.service.IUserService;
import com.mrti.shop.util.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;


    @GetMapping("/allUsers")
    public R getAllUsers()
    {
        List<User> users = userService.list();
        return R.success("成功取得所有用户",users);
    }

    @PostMapping("/addUser")
    @ApiOperation(value="新增用户")
    public R addUser(@RequestBody User user)
    {
        LocalDateTime createTime = LocalDateTime.now();
        LocalDateTime modifyTime = LocalDateTime.now();
        user.setCreateTime(createTime);
        user.setModifyTime(modifyTime);
        boolean flag = userService.save(user);
        if(flag)
        {
            return R.success("用户保存成功");
        }
        else
        {
            return R.error("用户保存失败");
        }
    }

    @PostMapping("/modifyUser")
    @ApiOperation(value="修改用户")
    public R modifyUser(@RequestBody User user)
    {
        LocalDateTime modifyTime = LocalDateTime.now();
        user.setModifyTime(modifyTime);
        boolean flag = userService.updateById(user);
        if(flag)
        {
            return R.success("用户修改成功");
        }
        else
        {
            return R.error("用户信息修改失败");
        }
    }

    @PostMapping("/queryUser")
    @ApiOperation(value="查询用户")
    public R queryUser(@RequestBody User user)
    {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,user.getUsername());
        lambdaQueryWrapper.eq(User::getPassword,user.getPassword());
        List<User> userList = userService.list(lambdaQueryWrapper);
        if(userList.size() != 0)
        {
            return R.success("该用户存在",userList);
        }
        else
        {
            return R.error("该用户不存在");
        }
    }

    @PostMapping("queryUser2")
    @ApiOperation(value="模糊查询")
    public R queryUser2(@RequestBody User user)
    {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(User::getUsername,user.getUsername());
        List<User> userList = userService.list(lambdaQueryWrapper);
        if(userList.size() != 0)
        {
            return R.success("查询到了用户",userList);
        }
        else
        {
            return R.error("没有查询到用户");
        }
    }

}
